import { useEffect, useRef, useState } from 'react'
import { NavBar, Tabs, Card, Button, PullToRefresh, InfiniteScroll, Toast } from 'antd-mobile'
// import { LeftOutline } from 'antd-mobile-icons'
import { useLocation, useNavigate } from 'react-router-dom'
import placeholder from '../../assets/placeholder.png'
import styles from './index.module.css'
import { fetchReceptionPage, applyLeaseApplication } from '../../services/api'

type HouseAcceptanceItem = {
  id: string | number
  contractNo: string
  title: string
  buildingInfo?: string
  floor: string
  roomNo: string
  area: string
  tenant: string
  idNo: string
  phone: string
  rentPerMonth: string
  deposit: string
  state?: number
  houseId: string | number
  applicationId?: string
}

export default function HouseAcceptance() {
  const navigate = useNavigate()
  const location = useLocation()
  const [tabKey, setTabKey] = useState<'pending' | 'accepted'>(() => {
    const sp = new URLSearchParams(location.search)
    return sp.get('tab') === 'accepted' ? 'accepted' : 'pending'
  })

  const [items, setItems] = useState<HouseAcceptanceItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  const [loaded, setLoaded] = useState(false)
  const pageRef = useRef(1)
  const sizeRef = useRef(10)
  const loadingRef = useRef(false)

  function toItem(it: any): HouseAcceptanceItem {
    return {
      id: it.id,
      contractNo: it.contractNo || '—',
      title: it.buildingEstateName || it.projectName || '—',
      buildingInfo: it.houseNo ? `-${it.houseNo}` : '',
      floor: it.buildingUnitName || '—',
      roomNo: it.houseNo || '—',
      area: it.bedRoomNum ? `${it.bedRoomNum} 室` : '—',
      tenant: it.applicationName || '—',
      idNo: '—',
      phone: it.phone || '—',
      rentPerMonth: typeof it.monthlyRent === 'number' ? `${it.monthlyRent}元` : '—',
      deposit: '—',
      state: typeof it.state === 'number' ? it.state : 0,
      houseId: it.houseId,
      applicationId: it.applicationId,
    }
  }

  async function queryPage(reset = false) {
    if (loadingRef.current) return
    loadingRef.current = true
    const stateParam = tabKey === 'pending' ? 0 : 1
    const res = await fetchReceptionPage({
      current: pageRef.current,
      size: sizeRef.current,
      state: stateParam,
    }).catch(() => null)
    if (res) {
      const list = (res.records || []).map((it: any) => toItem(it))
      setItems(prev => (reset ? list : [...prev, ...list]))
      const noMore = (res.current || 1) >= (res.pages || 1)
      setHasMore(!noMore)
      if (!noMore) pageRef.current += 1
    }
    loadingRef.current = false
    setLoaded(true)
  }

  useEffect(() => {
    pageRef.current = 1
    setItems([])
    setHasMore(true)
    queryPage(true)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tabKey])

  // 将当前 tab 写入 URL，便于返回时还原
  useEffect(() => {
    navigate(`/acceptance?tab=${tabKey}`, { replace: true })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tabKey])

  async function loadMore() {
    await queryPage(false)
  }

  async function onRefresh() {
    pageRef.current = 1
    setItems([])
    setHasMore(true)
    setLoaded(false)
    await queryPage(true)
    Toast.show('已刷新')
  }

  return (
    <div className={styles['accept-page']}>
      <NavBar className={styles['nav-title']} back={null}>
        接房列表
      </NavBar>

      <div className={styles['accept-header']}>
        <div className={styles['accept-tabs']}>
          <Tabs activeKey={tabKey} onChange={key => setTabKey(key as any)}>
            <Tabs.Tab title={<span className={styles['tab-title']}>待接房</span>} key="pending" />
            <Tabs.Tab title={<span className={styles['tab-title']}>已接房</span>} key="accepted" />
          </Tabs>
        </div>
      </div>

      <div className={styles['accept-list-scroll']}>
        <PullToRefresh onRefresh={onRefresh}>
          <div className={styles['accept-list']}>
            {loaded && items.length === 0 ? (
              <div className={styles['empty-wrap']}>
                <img src={placeholder} alt="empty" className={styles['empty-image']} />
                <div className={styles['empty-text']}>暂无数据</div>
              </div>
            ) : (
              items.map(item => (
                <Card
                  key={item.id}
                  style={{ borderRadius: 8, marginBottom: 12 }}
                  onClick={() => navigate(`/acceptance/${item.id}`)}
                >
                  <div className={styles['accept-contract']}>合同号：{item.contractNo}</div>

                  <div className={styles['accept-row']}>
                    <div className={styles['accept-info']}>
                      <div className={styles['accept-title']}>
                        {item.title}
                        <span className={styles['accept-sub']}>{item.buildingInfo}</span>
                      </div>

                      <div className={styles['accept-tags']}>
                        <span className={styles['accept-chip']}>{item.floor}</span>
                        <span className={styles['accept-chip']}>{item.roomNo}</span>
                      </div>

                      <div className={styles['accept-text']}>租期：2025年6月1日—2025年12月1日</div>
                      <div className={styles['accept-text']}>租户：{item.tenant}</div>
                      <div className={styles['accept-text']}>身份证号：{item.idNo}</div>
                      <div className={styles['accept-text']}>电话：{item.phone}</div>
                      <div className={styles['accept-text']}>月租金：{item.rentPerMonth}</div>
                      <div className={styles['accept-text']}>保证金：{item.deposit}</div>
                    </div>

                    <div
                      className={styles['accept-action']}
                      onClick={e => {
                        e.stopPropagation()
                        navigate(`/acceptance/${item.id}`)
                      }}
                    />
                  </div>
                  <div className={styles['accept-card-btn-wrap']}>
                    {item.state !== 1 && (
                      <Button
                        size="mini"
                        className={`${styles['accept-card-btn']} ${
                          item.state === 1 ? styles['accept-card-btn-warn'] : ''
                        }`}
                        style={{ fontSize: 10, height: 26, padding: '0 10px', lineHeight: '26px' }}
                        onClick={async e => {
                          e.stopPropagation()
                          if (item.state === 1) {
                            await applyLeaseApplication(
                              item.houseId as any,
                              item.applicationId as any,
                            )
                            Toast.show({ icon: 'success', content: '已发起退租申请' })
                          } else {
                            navigate(`/acceptance/${item.id}`)
                          }
                        }}
                      >
                        {item.state === 1 ? '申请退租' : '立即审核'}
                      </Button>
                    )}
                  </div>
                </Card>
              ))
            )}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </PullToRefresh>
      </div>
    </div>
  )
}
